package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * @program: hm-dianping
 * @description:
 * @author: Feng
 * @create: 2023-03-08 10:32
 **/

public class TokenFreshInterceptor implements HandlerInterceptor {
//    你都不是component，你注入什么
    StringRedisTemplate stringRedisTemplate;

    public TokenFreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        小写，并且是授权authorization
//        String token = request.getHeader("authentication");
        String token = request.getHeader("authorization");
        if(token==null) return true;
        String tokenKey = LOGIN_USER_KEY+token;
//        对hash结构的获取是使用entries
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(tokenKey);
//        将UserDTO再转回来
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        if(userDTO==null) return true;
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
//        将userDto存入ThreadLocal
        UserHolder.saveUser(userDTO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserHolder.removeUser();
    }
}
